<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="90px">
      <el-form-item label="客户名称" prop="customerId">
        <el-select v-model="queryParams.customerId" placeholder="请选择客户" filterable remote reserve-keyword clearable
                   :remote-method="searchCustomer" :loading="loadingCustomer" style="width: 240px;">
          <el-option v-for="item in optionsCustomer"
                     :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="编号" prop="nos">
        <el-input v-model="queryParams.nos" placeholder="请输入编号"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="发生日期" prop="occurDate">
        <el-date-picker v-model="dateRange"
                        style="display: flex;"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="发货编号" prop="sendNos">
        <el-input v-model="queryParams.sendNos" placeholder="请输入发货编号"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="发货日期" prop="sendDate">
        <el-date-picker clearable v-model="queryParams.sendDate"
                        type="date" value-format="yyyy-MM-dd" placeholder="请选择发货日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="回款编号" prop="payReturnNos">
        <el-input v-model="queryParams.payReturnNos" placeholder="请输入回款编号"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="回款日期" prop="payReturnDate">
        <el-date-picker clearable v-model="queryParams.payReturnDate"
                        type="date" value-format="yyyy-MM-dd" placeholder="请选择回款日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="金额" prop="amount">
        <el-input v-model="queryParams.amount" placeholder="请输入金额"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini"
                   @click="handleExport" v-hasPermi="['develop:FinanceAr:export']">导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table"
              show-summary :summary-method="getSummaries" :max-height="tableMaxHeight">
      <el-table-column type="selection" width="60" align="center"/>
      <el-table-column label="编号" align="center" prop="nos"/>
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ar_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="发生时间" align="center" prop="occurDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.occurDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="customerName"/>
      <el-table-column sortable align="center" label="发货编号" prop="sendNos">
        <template slot-scope="scope">
          <el-tooltip class="item" content="发货编号" effect="dark" placement="left-start">
            <span @click="handleSendDetail(scope.row)" style="color: #00afff;cursor:pointer;">
              {{ scope.row.sendNos }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="发货日期" align="center" prop="sendDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sendDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="回款编号" align="center" prop="payReturnNos"/>
      <el-table-column label="回款日期" align="center" prop="payReturnDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payReturnDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="期初应收" align="center" prop="deliveryMoney" >
        <template slot-scope="scope">
          <span v-if="scope.row.deliveryMoney>0">{{ accSub(scope.row.remainMoney,scope.row.deliveryMoney) }}</span>
          <span v-if="scope.row.acceptMoney>0">{{ accAdd(scope.row.remainMoney,scope.row.acceptMoney) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="本期应收" align="center" prop="deliveryMoney"/>
      <el-table-column label="本期回款" align="center" prop="acceptMoney"/>
      <el-table-column label="期末应收" align="center" prop="remainMoney"/>

    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList"/>
    <financeAr-form ref="form" @ok="getList"></financeAr-form>

    <lv-yifahuomingxi-detail-list ref="sendList"></lv-yifahuomingxi-detail-list>
  </div>
</template>

<script>
import {accAdd, accSub, deleteAction, downloadFile, getAction, isEmpty} from '@/api/manage'
import FinanceArForm from '@/views/develop/finance/financeAr/module/FinanceArForm'
import LvYifahuomingxiDetailList from "@/views/develop/lvYifahuomingxi/module/LvYifahuomingxiDetailList.vue";

export default {
  name: "FinanceArList",
  dicts:['ar_type'],
  components: {
    LvYifahuomingxiDetailList,
    FinanceArForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应收账款表格数据
      dataList: [],
      optionsCustomer: [],
      daterange: [],
      loadingCustomer:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nos: null,
        type: null,
        occurDate: null,
        customerId: null,
        customerName: null,
        sendId: null,
        sendNos: null,
        sendDate: null,
        payReturnId: null,
        payReturnNos: null,
        payReturnDate: null,
        amount: null,
        orderByColumn:"a.nos",
        isAsc:"asc"
      },
      url: {
        list: '/financeAr/financeAr/list',
        remove: '/financeAr/financeAr/',
        export: '/financeAr/financeAr/export',
      },
      tableMaxHeight: window.innerHeight - 320,
    };
  },
  created() {
    this.getList();
    window.addEventListener('resize', this.getTableHeight);
  },
  destroyed() {
    window.removeEventListener('resize', this.getTableHeight)
  },
  methods: {
    accAdd,
    accSub,
    /** 查询应收账款列表 */
    getList() {
      this.loading = true;
      this.addDateRange(this.queryParams, this.dateRange,"OccurDate")
      getAction(this.url.list, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTableHeight() {
      this.tableHeight = window.innerHeight - 320
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.form.handleAdd();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove, ids).then(response => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 先选择供应商
      if(isEmpty(this.queryParams.customerId)){
        this.$modal.msgError("请先选择客户");
        return;
      }
      downloadFile(this.url.export, this.queryParams);
    },

    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (column.property === "deliveryMoney"
          || column.property === 'acceptMoney'
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },

    async searchCustomer(queryString) {
      this.loadingCustomer = true;
      if (queryString) {
        let params = {
          "pageNum": 1,
          "pageSize": 20,
          "name": queryString
        };
        getAction("/goodsCustomer/goodsCustomer/list", params).then(response => {
          this.optionsCustomer = response.rows;
          this.loadingCustomer = false;
        });
      } else {
        this.optionsCustomer = [];
        this.loadingCustomer = false;
      }
    },

    handleSendDetail(row){
      this.$refs.sendList.handleShowBy(row.sendId);
    },

  }
};
</script>
